<script setup>
import VButton from "../button/VButton.vue";
import {onMounted, reactive, ref, watch} from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {
      return {};
    }
  },
  rules: {
    type: Object,
    default: () => {
      return {};
    }
  },
  width: {
    type: String,
    default: 'auto'
  },
  noFooter: {
    type: Boolean,
    default: true
  },
  footerJustify: {
    type: String,
    // 按钮对齐 left | center | right
    default: 'left'
  }
});
const emits = defineEmits(['confirm', 'close', 'update:modelValue']);
const formRef = ref(null);
// 实际表单数据
const formData = reactive({});
// 暂存表单数据,由于重置回显字段
const tempForm = reactive({});
const classes = {
  'left': 'footer-justify-left',
  'center': 'footer-justify-center',
  'right': 'footer-justify-right',
};
onMounted(() => {
  for (let formKey in props.modelValue) {
    tempForm[formKey] = props.modelValue[formKey];
    formData[formKey] = props.modelValue[formKey];
  }
});
// 监听 formData 表单数据，一旦发生变化，则更新父组件的数据
watch(() => formData, (newVal) => {
  // 发送事件通知父组件更新数据
  emits('update:modelValue', newVal);
}, {deep: true});
const click = (type) => {
  if (type === 'confirm') {
    // 发送事件通知父组件更新数据
    emits('update:modelValue', formData);
    formRef['value'].validate((valid) => {
      if (valid) {
        console.log('submit success!', formData)
        emits(type, formData);
      } else {
        return false;
      }
    });
  } else {
    formRef['value'].resetFields();
    for (let formKey in tempForm) {
      formData[formKey] = tempForm[formKey];
    }
    // 发送事件通知父组件更新数据
    emits('update:modelValue', formData);
    emits(type);
  }
};
</script>

<template>
  <el-form ref="formRef" style="width: 100%;" :model="formData" :rules="rules"
           :label-width="width">
    <slot name="default"/>
    <slot name="footer" v-if="noFooter">
      <el-form-item :class="classes[footerJustify]">
        <v-button @click="click('confirm')" name="确定" color="#1D93AB"/>
        <v-button @click="click('close')" name="取消"/>
      </el-form-item>
    </slot>
  </el-form>
</template>

<style scoped>
.footer-justify-left :deep(.el-form-item__content) {
  justify-content: left;
}

.footer-justify-center :deep(.el-form-item__content) {
  justify-content: center;
}

.footer-justify-right :deep(.el-form-item__content) {
  justify-content: right;
}
</style>